#encoding: utf-8
require 'uuidtools'
class MapsController < ApplicationController
  def track_register
    begin
      vehicle_no = params[:vehicle_no]
      session_id = params[:session_id].strip if params[:session_id]
      if vehicle_no and !vehicle_no.strip.empty?
        #生成uuid，封装车号并存入注册队列
        mq = Opal::Mq::Mq.new("Q_OB_REGS")
        unless session_id
          session_id = UUIDTools::UUID.timestamp_create().to_s
        end
        mq.set({session_id => [vehicle_no]})
        heartbeat session_id
        render :json => {:status => 'ok', :notice => "已跟踪", :session_id => session_id}
      else
        render :json => {:status => 'exception', :notice => "页面异常，请刷新页面试试"}
      end
    rescue Exception => e
      logger.error "track register exception: #{e.message}"
      render :json => {:status => 'exception', :notice => "系统异常，稍后再试"}
    end
  end

  def track_fetch_gps
    begin
      session_id = params[:session_id].strip if params[:session_id]
      if session_id
        heartbeat session_id
        mq = Opal::Mq::Mq.new("Q_OB_SESSION")
        if mq.size(session_id) > 0
          gps_data = mq.get_all(session_id) #[  {lk-001=>[gpsObj1, gpsObj2]},  {lk-002=>[gpsObj1, gpsObj2]}, {lk-001=>[gpsObj1, gpsObj2]} ]

        end
        logger.info "get all from mq #{session_id}, data is #{gps_data}"
        if gps_data.nil? || gps_data.empty?
          render :json => {:status => 'empty', :notice => "暂无数据，无法跟踪!\n\r如需要，请即使与服务提供商联系"}
        else
          gps_hash = {}
          gps_data.each do |vehicle_gps_hash|
            if vehicle_gps_hash
              vehicle_gps_hash.each do |vehicle_no, gps_array|
                unless gps_hash[vehicle_no]
                  gps_hash[vehicle_no] = []
                end
                gps_hash[vehicle_no].concat gps_array
              end
            end
          end
          render :json => {:status => 'ok', :gps_objs => gps_hash} #{'lk-001'=>[gps1, gps2],  'lk-002'=>[gps3, gps4]}
        end
      end
    rescue Exception => e
      logger.error "Exception occurred when tracking, #{e.message}"
      render :json => {:status => 'exception', :notice => "系统异常，稍后再试"}
    end

  end

  def track_unregister
    begin
      vehicle_no = params[:vehicle_no].strip if params[:vehicle_no]
      session_id = params[:session_id].strip if params[:session_id]
      if vehicle_no and !vehicle_no.strip.empty?
        #生成uuid，封装车号并存入注册队列
        mq = Opal::Mq::Mq.new("Q_OB_UNREG")
        if session_id
          mq.set({session_id => [vehicle_no]})
          heartbeat session_id
          render :json => {:status => 'ok', :notice => "已取消"}
          return
        end
      end
      render :json => {:status => 'exception', :notice => "页面异常，请刷新页面试试"}
    rescue
      render :json => {:status => 'exception', :notice => "系统异常，稍后再试"}
    end
  end



  private
  def heartbeat(session_id)
    mc = Opal::Mc::Mc.new("HB_MC")
    mc.set(session_id, true) if session_id
  end

  skip_before_filter :require_login
end
